// pages/product/product.js
var cart = require('../../utils/cart');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: 'https://car.ispongecity.com/lesson/files', 
    catalogs: [],
    catalog: '全部',
    categories: [],
    category: '全部',
    source: [],
    products: [],
    keyword: '',
    show: false,
    order: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.request({
      url: 'https://car.ispongecity.com/lesson/config/product',
      success: (result) => {
        this.setData({
          catalogs: result.data.catalogs
        })
      }
    })
    wx.request({
      url: 'https://car.ispongecity.com/lesson/products',
      success: (result) => {
        this.setData({
          source: result.data,
          products: result.data
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  filter(e) {
    this.setData({
      products: this.data.source.filter(item => item.name.indexOf(e.detail.value) != -1)
    });
  },

  clear() {
    this.setData({
      products: this.data.source
    });
  },

  switch(e) {
    this.setData({
      show: !this.data.show,
      catalog: '全部',
      categories: [],
      category: '全部',
      products: this.data.source
    });
  },

  changeCatalog(e) {
    const code = e.currentTarget.dataset.code;
    const catalog = this.data.catalogs.find(item => item.code == e.currentTarget.dataset.code);
    const category = '全部';
    this.setData({
      catalog: code,
      category: category,
      categories: catalog ? catalog.children : [],
      products: this.data.source.filter(item => code == '全部' || item.catalog == code)
    });
  },

  changeCategory(e) {
    const category = e.currentTarget.dataset.code;
    const catalog = this.data.catalog;
    this.setData({
      category: category,
      products: this.data.source.filter(item => catalog == '全部' || item.catalog == catalog).filter(item => category == '全部' || item.category == category)
    })
  },

  navi2cart() {
    wx.navigateTo({url: '../cart/cart'});
  },

  add2cart(e) {
    const item = this.data.source.find(item => item._id == e.currentTarget.dataset.item._id);
    if (item) {
      item.badge = item.badge || 0;
      item.badge += 1;
      cart.plus(item);
      this.setData({
        products: this.data.products,
        order: true
      });
    }
  }
})